package com.movie.service;

import com.movie.dto.UserWatchHistoryDTO;
import com.movie.entity.UserWatchHistory;
import com.movie.entity.User;
import com.movie.entity.Movie;
import com.movie.repository.UserWatchHistoryRepository;
import com.movie.repository.UserRepository;
import com.movie.repository.MovieRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class UserWatchHistoryService {
    
    private final UserWatchHistoryRepository userWatchHistoryRepository;
    private final UserRepository userRepository;
    private final MovieRepository movieRepository;
    @Transactional
    // 添加或更新观看记录
    public UserWatchHistoryDTO addOrUpdateWatchHistory(Long userId, Long movieId, Integer watchTime, Integer lastPosition) {
        User user = userRepository.findById(userId)
            .orElseThrow(() -> new RuntimeException("用户不存在"));
        Movie movie = movieRepository.findById(movieId)
            .orElseThrow(() -> new RuntimeException("电影不存在"));
        
        Optional<UserWatchHistory> existing = userWatchHistoryRepository.findByUserAndMovie(user, movie);
        UserWatchHistory history;
        
        if (existing.isPresent()) {
            history = existing.get();
            history.setWatchTime(watchTime);
            history.setLastPosition(lastPosition);
        } else {
            history = new UserWatchHistory();
            history.setUser(user);
            history.setMovie(movie);
            history.setWatchTime(watchTime);
            history.setLastPosition(lastPosition);
        }
        
        UserWatchHistory saved = userWatchHistoryRepository.save(history);
        return convertToDTO(saved);
    }
    
    // 获取用户观看历史
    public List<UserWatchHistoryDTO> getUserWatchHistory(Long userId) {
        return userWatchHistoryRepository.findByUser_IdOrderByUpdatedAtDesc(userId).stream()
            .map(this::convertToDTO)
            .collect(Collectors.toList());
    }
    
    // 获取用户最近的观看历史
    public List<UserWatchHistoryDTO> getRecentWatchHistory(Long userId) {
        return userWatchHistoryRepository.findTop10ByUser_IdOrderByUpdatedAtDesc(userId).stream()
            .map(this::convertToDTO)
            .collect(Collectors.toList());
    }
    @Transactional
    // 删除单个观看记录
    public void deleteWatchHistory(Long id, Long userId) {
        UserWatchHistory history = userWatchHistoryRepository.findById(id)
            .orElseThrow(() -> new RuntimeException("观看记录不存在"));
        
        if (!history.getUser().getId().equals(userId)) {
            throw new RuntimeException("无权删除此记录");
        }
        
        userWatchHistoryRepository.deleteById(id);
    }
    
    @Transactional
    // 清除用户观看历史
    public void clearWatchHistory(Long userId) {
        userWatchHistoryRepository.deleteByUser_Id(userId);
    }
    
    // 统计用户观看历史数量
    public long countUserWatchHistory(Long userId) {
        return userWatchHistoryRepository.countByUser_Id(userId);
    }
    
    private UserWatchHistoryDTO convertToDTO(UserWatchHistory history) {
        UserWatchHistoryDTO dto = new UserWatchHistoryDTO();
        dto.setId(history.getId());
        dto.setUserId(history.getUser().getId());
        dto.setUsername(history.getUser().getUsername());
        dto.setMovieId(history.getMovie().getId());
        dto.setMovieTitle(history.getMovie().getTitle());
        dto.setMovieCover(history.getMovie().getCover());
        dto.setWatchTime(history.getWatchTime());
        dto.setLastPosition(history.getLastPosition());
        dto.setCreatedAt(history.getCreatedAt());
        dto.setUpdatedAt(history.getUpdatedAt());
        dto.setYear(history.getMovie().getYear());
        return dto;
    }
}